/**
 * Created by Mark_ren on 2016/11/7.
 * 苟富贵,無相忘
 */
var express = require('express');
var router = express.Router();
var moment = require("moment");

var co = require('co');
var seqModule = require('./createModules');

var seq = new seqModule();



//查询(返回百问百答首页内容)
router.get('/getAnswersWxList', function(req, res, next) {
    co(function () {
        var type="";
        if(req.query.type==1){//代表了三种查询，分别是1:查询我提问的
            type+=" and ans.CREATE_USER= '"+req.query.create_user+"'";

        }else if(req.query.type==2){//查询我回答的
            type+=" and uCount>0 ";
        }else if(req.query.type==3){//查询我评论的
            type+=" and ans.pCount>0 ";
        }
        if(req.query.title!=""&&req.query.title!=null){
            type+=" and ans.title like '%"+req.query.title+"%'" ;
        }
        if(req.query.codeId!=null&&req.query.codeId!=""){
            type+=" and ans.ID in (select ANSWERS_ID from qcc_answers_dic where 1=1 and DIC_ID IN ("+req.query.codeId+")) ";

        }
        seq.sequelize.query("select * from (select ans.ID,ans.TITLE,ans.CREATE_TIME,ans.STATUS ,ans.CREATE_USER,ans.TOP_TIME," +
            " (select count(id)   from QCC_answers where ans.id= PARENTID LIMIT 1) as aCount," +
            " (select count(id)   from QCC_answers where ans.id= PARENTID and create_user='"+req.query.createUser+"' LIMIT 1) as uCount," +
            " (select count(id)   from qcc_answers_comment as t where  t.answers_id in (select  id from tp_ccdt.qcc_answers where QCC_answers.PARENTID=ans.ID) " +
            " and t.member_id='"+req.query.createUser+"' )as pCount,"+
            " (select GROUP_CONCAT(CODE_DESC separator ' ') from qcc_dictionary as d,tp_ccdt.qcc_answers_dic as ad" +
            " where d.CODE_ID=ad.DIC_ID and ad.ANSWERS_ID=ans.ID) as biaoqian" +
            "  from QCC_answers as ans  where ans.STATUS=10051001  and ans.SOFT_DEL = 1 ) as ans where 1=1 "+type +" order by ans.TOP_TIME desc, ans.CREATE_TIME desc").spread(function(result){
            res.json({"success":true,"result":result});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'查询失败'});
        console.log(e);
    })
});

//返回问题与对应详细内容
router.get('/getAnswersPcList', function(req, res, next) {
    co(function () {
        var status=10051001;
        var total="";
        var title="";
        var id ="";
        var page=parseInt(req.query.page);
        var rows=parseInt(req.query.rows);
        if(req.query.status!=null&&req.query.status!=""){
            status=req.query.status;
        }
        if(req.query.title!=null&&req.query.title!="undefined"){
            title=req.query.title;
        }
        if(req.query.id!=null&&req.query.id!="undefined"){
            id=" and parentid = '"+req.query.id+"'";
        }
        seq.sequelize.query("select count(an.id) as total ," +
            "(select count(id) as aCount  from QCC_answers where an.id= PARENTID LIMIT 1) as aCount" +
            " from QCC_answers as an ,member as m where an.CREATE_USER = m.open_id  and an.SOFT_DEL=1 " +
            " and an.STATUS="+status+" and an.title like '%"+title+"%' "+id).spread(function(result){
            total=result[0].total;
        });
        seq.sequelize.query("select an.id,an.TITLE,an.CREATE_TIME,an.TOP_TIME as topTime,an.adopt,m.open_id,m.name,m.hospital_name,m.hospital_offices," +
            "(select count(id) as aCount  from QCC_answers where an.id= PARENTID LIMIT 1) as aCount" +
            " from QCC_answers as an ,member as m where an.CREATE_USER = m.open_id  and an.SOFT_DEL=1 " +
            " and an.STATUS="+status+" and an.title like '%"+title+"%' "+id +" order by an.TOP_TIME desc,an.CREATE_TIME desc limit "+page*rows+","+(page+1)*rows+";").spread(function(result){
            res.json({"success":true,"total":total,"msg":"查询成功","result":result});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'查询失败'});
        console.log(e);
    })
});

//查询问题详情（回复详情）
router.get('/getAnswersWxDetil', function(req, res, next) {
    co(function () {
        var parentId=req.query.id;
        var memberId=req.query.memberId;
        seq.sequelize.query("select ans.id,ans.title,ans.parentid,ans.CREATE_USER,ans.create_time,ans.adopt,ans.status,m.name," +
            " (select count(id)   from qcc_answers_comment where ans.id= answers_id LIMIT 1) as pinglun," +
            " (select count(id)   from qcc_answers_liked where ans.id= course_id LIMIT 1) as dianzan," +
            " (select count(id)   from qcc_answers_comment where ans.id= answers_id and member_id = '"+memberId+"' LIMIT 1) as pinglun1,"+
            " (select count(id)   from qcc_answers_liked where ans.id= course_id and member_id = '"+memberId+"' LIMIT 1) as dianzan1,"+
            " (select count(id)   from qcc_log where ans.status=10051001 and ans.id=title ) as liulan" +
            " from  qcc_answers as ans ,member as m where ans.create_user = m.open_id  and ans.soft_del=1" +
            " and ( ans.id ='"+parentId+"' or ans.parentid ='" +parentId+"') order by ans.STATUS ,ans.ADOPT desc,ans.create_time").spread(function(result){
                res.json({"success":true,"result":result});

        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'查询失败'});
        console.log(e);
    })
});


//添加百问百答问题
router.get('/addAnswers', function(req, res, next) {
    co(function () {
        var codeIds= new Array();
        var uuids=new Array();
        codeIds=req.query.codeIds.split(","); //字符分割
        uuids=req.query.uuids.split(",");
        var insertSql="INSERT INTO qcc_answers_dic (ID, ANSWERS_ID, DIC_ID, HFIELD1, HFIELD2, HFIELD3) VALUES ";
        for(var i =0;i<codeIds.length-1;i++){
            insertSql+="('"+uuids[i]+"', '"+req.query.id+"', "+codeIds[i]+", null, null, null),";
        }
        insertSql+="('"+uuids[codeIds.length-1]+"', '"+req.query.id+"', "+codeIds[codeIds.length-1]+", null, null, null);";
        console.log(insertSql);
        req.query.createTime=moment().format("YYYY-MM-DD HH:mm:ss");
        seq.sequelize.query(insertSql).then(function(results){

        });
        req.query.title = decodeURI(req.query.title);
        seq.answersModule.create(req.query).then(function(results){
            res.json({"success":true,"result":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'添加失败'});
        console.log(e);
    })
});


//添加百问百答回答
router.get('/addAnswersReturn', function(req, res, next) {
    co(function () {
        req.query.createTime=moment().format("YYYY-MM-DD HH:mm:ss");
        seq.answersModule.create(req.query).then(function(results){
            res.json({"success":true,"result":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'添加失败'});
        console.log(e);
    })
});


//是否采纳
router.get('/updateAnswers', function(req, res, next) {
    co(function () {
        var params={};
        var paramT={};
        var paramU={'id':req.query.id};
        if(req.query.adopt != undefined&&req.query.adopt!=null){
            params["adopt"]=req.query.adopt;
        }
        paramT["where"]=paramU;
        seq.answersModule.update(params,paramT).then(function(results){
            res.json({"success":true,"msg":"修改成功","result":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'修改失败'});
        console.log(e);
    })
});

//是否删除（软删主问题表）
router.get('/delAnswers', function(req, res, next) {
    co(function () {
        var paramT={};
        var paramD={};
        var params=req.query.id;
        var arr=params.split(",");
        var paramU={'id':[arr]};
        if(req.query.id != undefined&&req.query.id!=null){
            paramD["softDel"]=0
        }
        paramT["where"]=paramU;
        seq.answersModule.update(paramD,paramT).then(function(results){
            res.json({"success":true,"msg":"修改成功","result":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'修改失败'});
        console.log(e);
    })
});

//是否置顶（置顶TOP_TIME）
router.get('/updAnswers', function(req, res, next) {
    co(function () {
        var params={};
        var paramT={};
        var paramU={'id':req.query.id};
        if(req.query.topTime!=0&&req.query.topTime!=""){
            params["topTime"]=moment().format("YYYY-MM-DD HH:mm:ss");
        }else {
            params["topTime"]=req.query.topTime;
        }
        paramT["where"]=paramU;
        seq.answersModule.update(params,paramT).then(function(results){
            res.json({"success":true,"msg":"修改成功","result":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'修改失败'});
        console.log(e);
    })
});

//点赞
router.get('/addAnswersLike', function(req, res, next) {
    co(function () {
        req.createTime = decodeURI(req.query.createTime);
        seq.answersLikedModule.create(req.query).then(function(results){
            res.json({"success":true,"result":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'添加失败'});
        console.log(e);
    })
});
//取消赞(删除)
router.get('/delAnswersLike', function(req, res, next) {
    co(function () {

        seq.answersLikedModule.destroy({'where':{'id':id}}).then(function(results){
            res.json({"success":true,"msg":"取消成功","result":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'取消失败'});
        console.log(e);
    })
});
module.exports = router;